<template>
  <div class="audit-clause-container">
    <div class="header">
      <div class="header-content flex justify-between items-center">
        <h2 class="text-xl font-bold text-gray-800">
          {{ isLegalSpecialist ? '法务审核 - 条款审核' : '财务审核 - 条款审核' }}
        </h2>
        <button @click="goBack" class="btn btn-secondary flex items-center px-4 py-2 rounded-lg bg-gray-600 text-white hover:bg-gray-700 transition-colors">
          <i class="fa fa-arrow-left mr-2"></i>返回
        </button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-indicator flex flex-col items-center justify-center py-16">
      <div class="spinner w-12 h-12 border-4 border-gray-200 border-t-green-500 rounded-full animate-spin"></div>
      <p class="mt-4 text-gray-600">加载中...</p>
    </div>

    <!-- 错误消息 -->
    <div v-if="errorMessage" class="error-message flex items-start p-4 mb-6 bg-red-50 border-l-4 border-red-400 text-red-700 rounded-r-lg">
      <i class="fa fa-exclamation-circle mr-3 mt-1"></i>
      <span>{{ errorMessage }}</span>
    </div>

    <!-- 条款审核表单 -->
    <div v-if="!loading && clause" class="card mt-6 bg-white rounded-xl shadow-sm border border-gray-200">
      <div class="card-header bg-green-500 text-white px-6 py-3 rounded-t-xl">
        <h3 class="text-lg font-semibold">条款审核</h3>
      </div>
      <div class="card-body p-6">
        <div class="mb-6">
          <label for="clauseContent" class="form-label block text-sm font-medium text-gray-700 mb-2">条款内容</label>
          <div class="relative">
            <textarea
                id="clauseContent"
                class="form-control w-full px-4 py-3 border border-gray-300 rounded-lg bg-gray-50 text-gray-700 resize-none"
                rows="5"
                readonly
                v-model="clause.content"
            ></textarea>
            <div class="absolute inset-0 pointer-events-none border border-gray-200 rounded-lg"></div>
          </div>
        </div>

        <div class="mb-6">
          <label class="form-label block text-sm font-medium text-gray-700 mb-2">审核状态</label>
          <div class="flex space-x-6">
            <div class="form-check flex items-center">
              <input
                  class="form-check-input h-4 w-4 text-green-500 focus:ring-green-500 border-gray-300 rounded"
                  type="radio"
                  id="approved"
                  value="APPROVED"
                  v-model="auditStatus"
              >
              <label class="form-check-label ml-2 text-gray-700" for="approved">通过</label>
            </div>
            <div class="form-check flex items-center">
              <input
                  class="form-check-input h-4 w-4 text-red-500 focus:ring-red-500 border-gray-300 rounded"
                  type="radio"
                  id="rejected"
                  value="REJECTED"
                  v-model="auditStatus"
              >
              <label class="form-check-label ml-2 text-gray-700" for="rejected">拒绝</label>
            </div>
          </div>
        </div>

        <div class="mb-6">
          <label for="opinion" class="form-label block text-sm font-medium text-gray-700 mb-2">审核意见</label>
          <textarea
              id="opinion"
              class="form-control w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent transition-colors"
              rows="3"
              v-model="opinion"
              placeholder="请输入审核意见..."
          ></textarea>
          <p v-if="auditStatus === 'REJECTED' && !opinion" class="mt-1 text-red-500 text-xs italic">拒绝时必须提供审核意见</p>
        </div>

        <div class="flex justify-end">
          <button
              @click="submitAudit"
              class="btn btn-primary flex items-center px-6 py-2.5 bg-green-500 text-white rounded-lg hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 transition-all"
              :disabled="!auditStatus || (auditStatus === 'REJECTED' && !opinion)"
          >
            <i class="fa fa-save mr-2"></i>
            <span>提交审核</span>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { ref, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'

export default {
  name: 'AuditClause',
  setup() {
    const store = useStore()
    const router = useRouter()
    const route = useRoute()

    const contractId = ref(null)
    const clauseId = ref(null)
    const loading = ref(true)
    const errorMessage = ref('')
    const clause = ref(null)
    const auditStatus = ref('')
    const opinion = ref('')

    // 用户信息
    const employeeId = ref(null)
    const employeePosition = ref(null)
    const isLegalSpecialist = ref(false)
    const isFinanceSpecialist = ref(false)

    // 返回上一页
    const goBack = () => {
      if (contractId.value) {
        router.push(`/employee/audit-contract/${contractId.value}`)
      } else {
        router.push('/employee/audit-contracts')
      }
    }

    // 获取条款详情 - 增强错误处理
    const fetchClause = () => {
      loading.value = true
      errorMessage.value = ''

      // 确保合同ID和条款ID存在
      if (!contractId.value || !clauseId.value || !employeeId.value) {
        errorMessage.value = '数据加载失败：缺少必要参数'
        loading.value = false
        return
      }

      // 确定审核类型
      const auditType = isLegalSpecialist.value ? 'legal' : 'finance'

      // 获取条款详情
      const url = `/auth/contracts/${contractId.value}/clauses/${clauseId.value}/audit`
      console.log('请求获取条款详情:', url)

      axios.get(url, {
        headers: {
          'X-Employee-Id': employeeId.value,
          'X-Employee-Position': employeePosition.value
        },
        params: {
          type: auditType
        }
      })
          .then(response => {
            console.log('条款详情响应:', response.data)
            clause.value = response.data
            // 初始化审核状态
            auditStatus.value = clause.value.auditStatus === 'PENDING' ? '' : clause.value.auditStatus
          })
          .catch(error => {
            console.error('获取条款详情失败', error)
            if (error.response) {
              switch (error.response.status) {
                case 403:
                  errorMessage.value = '您没有权限审核此条款'
                  break
                case 404:
                  errorMessage.value = '条款不存在'
                  break
                default:
                  errorMessage.value = '获取条款详情失败，请稍后再试'
              }
            } else {
              errorMessage.value = '网络错误，无法获取条款详情'
            }
          })
          .finally(() => {
            loading.value = false
          })
    }

    // 提交审核 - 增强参数验证
    const submitAudit = () => {
      if (!contractId.value || !clauseId.value) {
        errorMessage.value = '提交失败：缺少必要参数'
        return
      }

      if (!auditStatus.value) {
        errorMessage.value = '请选择审核状态'
        return
      }

      if (auditStatus.value === 'REJECTED' && !opinion.value) {
        errorMessage.value = '拒绝时请提供审核意见'
        return
      }

      // 确定审核类型
      const auditType = isLegalSpecialist.value ? 'legal' : 'finance'

      // 提交审核 - 显示加载状态
      loading.value = true
      axios.put(`/auth/contracts/${contractId.value}/clauses/${clauseId.value}/audit`, {
        auditStatus: auditStatus.value,
        opinion: opinion.value,
        type: auditType
      }, {
        headers: {
          'X-Employee-Id': employeeId.value,
          'X-Employee-Position': employeePosition.value
        }
      })
          .then(() => {
            alert('审核已提交')
            router.push(`/employee/audit-contract/${contractId.value}`)
          })
          .catch(error => {
            console.error('提交审核失败', error)
            errorMessage.value = error.response?.data?.message || '提交审核失败，请稍后再试'
          })
          .finally(() => {
            loading.value = false
          })
    }

    onMounted(() => {
      // 从路由获取合同ID和条款ID - 增加异常处理
      try {
        contractId.value = parseInt(route.params.contractId)
        clauseId.value = parseInt(route.params.clauseId)
      } catch (e) {
        console.error('路由参数解析失败', e)
        errorMessage.value = '数据解析失败，请重试'
        loading.value = false
        return
      }

      // 初始化用户信息
      employeeId.value = store.state.user?.id
      employeePosition.value = store.state.user?.position
      isLegalSpecialist.value = store.state.user?.position === 'LEGAL_SPECIALIST'
      isFinanceSpecialist.value = store.state.user?.position === 'FINANCE_SPECIALIST'

      // 监听用户信息变化
      watch([
        () => store.state.user?.id,
        () => store.state.user?.position
      ], () => {
        employeeId.value = store.state.user?.id
        employeePosition.value = store.state.user?.position
        isLegalSpecialist.value = store.state.user?.position === 'LEGAL_SPECIALIST'
        isFinanceSpecialist.value = store.state.user?.position === 'FINANCE_SPECIALIST'
        fetchClause()
      })

      fetchClause()
    })

    return {
      loading,
      errorMessage,
      clause,
      auditStatus,
      opinion,
      goBack,
      submitAudit,
      isLegalSpecialist,
      isFinanceSpecialist
    }
  }
}
</script>

<style scoped>
.audit-clause-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.header {
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.loading-indicator {
  min-height: 200px;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: #42b983;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.error-message {
  display: flex;
  align-items: flex-start;
}

.card {
  border: 1px solid #e2e8f0;
  border-radius: 0.5rem;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}

.card-header {
  padding: 0.75rem 1.25rem;
  border-bottom: 1px solid #e2e8f0;
  background-color: #f8fafc;
  border-top-left-radius: 0.375rem;
  border-top-right-radius: 0.375rem;
}

.card-body {
  padding: 1.25rem;
}

.form-label {
  font-weight: 500;
  color: #4b5563;
}

.form-control {
  width: 100%;
  padding: 0.5rem 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 0.375rem;
  transition: all 0.2s;
}

.form-control:focus {
  outline: none;
  border-color: #42b983;
  box-shadow: 0 0 0 3px rgba(66, 185, 131, 0.2);
}

.btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 0.5rem 1rem;
  border-radius: 0.375rem;
  font-weight: 500;
  cursor: pointer;
  border: none;
  transition: all 0.2s;
}

.btn-primary {
  background-color: #42b983;
  color: white;
}

.btn-primary:hover {
  background-color: #369c6b;
  box-shadow: 0 4px 6px -1px rgba(66, 185, 131, 0.4);
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background-color: #5a6268;
}

.btn-gray {
  background-color: #e5e7eb;
  color: #9ca3af;
  cursor: not-allowed;
}

.btn-gray:hover {
  background-color: #e5e7eb;
  box-shadow: none;
}

.contract-name {
  margin-bottom: 0.75rem;
}

.contract-info {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 1rem;
}

.clauses-section {
  margin-top: 1.5rem;
}

.empty-message {
  padding: 2rem;
  border: 2px dashed #e2e8f0;
  border-radius: 0.5rem;
}

.sign-area {
  margin-top: 1.5rem;
}
</style>